package com.hupu.jrs.ui.login

import android.text.TextUtils
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.otto.LoginSuccessEvent
import com.hupu.jrs.util.SecurityUtil
import com.hupu.jrs.util.ToastUtil
import com.squareup.otto.Bus
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import javax.inject.Inject
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1

/**
 * Created by sll on 2016/3/10.
 */
@PerActivity
class LoginPresenter @Inject
constructor(private val mGameApi: GameApi, private val mBus: Bus, private val mUserDao: UserDao, private val mUserStorage: UserStorage) : LoginContract.Presenter {

    private var mLoginView: LoginContract.View? = null
    private val user = User()
    private var mSubscription: Subscription? = null

    override fun login(userName: String, passWord: String) {
        if (TextUtils.isEmpty(userName)) {
            mLoginView!!.showUserNameError("请输入用户名")
            return
        }
        if (TextUtils.isEmpty(passWord)) {
            mLoginView!!.showPassWordError("请输入密码")
            return
        }
        mLoginView!!.showLoading()
        mSubscription = mGameApi.login(userName, SecurityUtil.getMD5(passWord))
                .flatMap(Func1<Any, Observable<Any>> { loginData ->
                    if (loginData != null && loginData.is_login === 1) {
                        val data = loginData.result
                        var cookie = ""
                        try {
                            cookie = URLDecoder.decode(Constants.Cookie, "UTF-8")
                        } catch (e: UnsupportedEncodingException) {
                            e.printStackTrace()
                        }

                        val uid = cookie.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                        user.setUid(uid)
                        user.setToken(data.token)
                        user.setCookie(cookie)
                        user.setUserName(data.username)
                        return@Func1 mGameApi.getUserInfo(uid)
                    }
                    null
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Action1<Any> { userData ->
                    if (userData != null && userData.result != null) {
                        val data = userData.result
                        user.setIcon(data.header)
                        user.setThreadUrl(data.bbs_msg_url)
                        user.setPostUrl(data.bbs_post_url)
                        user.setRegisterTime(data.reg_time_str)
                        user.setSchool(data.school)
                        user.setSex(data.gender)
                        user.setLocation(data.location_str)
                        mUserStorage.login(user)
                        insertOrUpdateUser(user)
                        ToastUtil.showToast("登录成功")
                        mBus.post(LoginSuccessEvent())
                        mLoginView!!.loginSuccess()
                    } else {
                        mLoginView!!.hideLoading()
                        ToastUtil.showToast("登录失败，请检查您的网络")
                    }
                }, Action1<Throwable> { throwable ->
                    throwable.printStackTrace()
                    mLoginView!!.hideLoading()
                    ToastUtil.showToast("登录失败，请检查您的网络")
                })
    }

    private fun insertOrUpdateUser(user: User) {
        val users = mUserDao.queryBuilder().where(UserDao.Properties.Uid.eq(user.getUid())).list()
        if (!users.isEmpty()) {
            user.setId(users.get(0).getId())
        }
        mUserDao.insertOrReplace(user)
    }

    override fun attachView(view: LoginContract.View) {
        mLoginView = view
    }

    override fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mLoginView = null
    }
}
